package com.upcode.weighing.oauthserver.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;

import javax.servlet.http.HttpServletResponse;

/**
 * @author ZYW
 * @date 2018/2/2
 */
@Configuration
@EnableResourceServer
//开启基于方法的声明式权限控制
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    public static String USER_STATUS_KEY = "USER_STATUS_KEY:";

    private static final String[] AUTH_WHITELIST = {

            // -- swagger ui
            "/swagger-resources/**",
            "/swagger-ui.html",
            "/v2/api-docs",
            "/webjars/**",
            //业务放行接口
            //短信注册验证码
            "/sms/regist",
            //app小程序用户注册
            "/user/register",
            //登陆验证码接口
            "/sms/login",
            //修改密码
            "/user/updatePwd",
            //检查手机号码是否已经注册
            "/user/checkMobileOnly/**",
            //小程序统一下单回调
            "/miniapp/order/notify",
            //app统一下单回调
            "/app/order/notify",
            //免密支付签约回调
            "/pap/contract/notify",
            //免密支付下单回调
            "/pap/order/notify",
            //统一退款回调地址
            "/unified/refund/notify",
            "/etcrefundrec/refund/notify",

            //退款回调业务地址
            "/refund/callback",
            "/refundRec/callback",
            //首页banner
            "/home/banners",
            //资源下载
            "/file/download/**",
            //刷卡支付
            "/paygate/**",

            //刷卡支付测试接口
            "/test/paygate/**",

            //发送消息
            "/msg_template/send",

            //App视图
            "/view/**",
            //天山行门户登陆接口
            "/tsxGateway/login",
            //天山行数据查询相关接口
            "/tsxGatewayData/**",
            "/api",
            "/etcrefundrec/**",

            "/file/sepVehDownLoad/**"
    };


    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
                .csrf().disable()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .exceptionHandling()
                .authenticationEntryPoint((request, response, authException) -> response.sendError(HttpServletResponse.SC_UNAUTHORIZED))
                .and()
                .authorizeRequests().antMatchers(AUTH_WHITELIST).permitAll()
                .anyRequest().authenticated()
                .and()
                .httpBasic().disable();
    }

    /*@Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources.authenticationEntryPoint((request,response,authException) -> {
            String type = stringRedisTemplate.boundValueOps(USER_STATUS_KEY).get();
            LOGGER.info("401类型1：" + type);
            //stringRedisTemplate.delete(USER_STATUS_KEY);
            LOGGER.info("401类型2：" + type);
            String message;
            LOGGER.info(StringUtils.isNotEmpty(type) + "");
            LOGGER.info(StringUtils.equals("2",type) + "");
            if(StringUtils.equals("1",type)) {
                LOGGER.info("--------------------------------");
                message ="用户被禁用";
            } else if(StringUtils.equals("2",type)) {
                LOGGER.info("=================================");
                message ="用户已在其他终端登陆";
            } else if(StringUtils.isEmpty(type)){
                LOGGER.info("++++++++++++++++++++++++++++++++++++");
                message ="令牌失效，请重新登陆";
            } else {
                message ="令牌失效，请重新登陆2222";
            }
            LOGGER.info(message);

            Map<String,String> map = new HashMap<>();
            map.put("code", "401");
            map.put("message", message);
            map.put("timestamp", String.valueOf(System.currentTimeMillis()));
            response.setContentType("application/json;charset=UTF-8");
            response.setHeader("Access-Control-Allow-Origin","*");
//            response.setHeader("Cache-Control", "no-cache");
//            response.setHeader("Pragma", "no-cache");
//            response.setDateHeader("Expires", 0);
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            try {
//                ObjectMapper mapper = new ObjectMapper();
                LOGGER.info(new ObjectMapper().writeValueAsString(map));
//                //mapper.writeValue(response.getOutputStream(), map);
//                IOUtils.write(mapper.writeValueAsString(map),response.getOutputStream(),"UTF-8");
                response.getOutputStream().write(new ObjectMapper().writeValueAsString(map).getBytes());
            } catch (Exception e) {
                throw new ServletException();
            }
        });
    }*/
}
